package com.ruoyi.web.service.impl;


import com.alibaba.fastjson2.JSON;
import com.ruoyi.web.domain.DyLoginRes;
import com.ruoyi.web.domain.WechatLoginRes;
import com.ruoyi.web.service.ThirdPartLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
class ThirdPartLoginServiceImpl implements ThirdPartLoginService {

    @Value("${wechat.auth.code2Session}")
    private String wechatCodeSessionUrl;
    @Value("${wechat.appid}")
    private String wechatAppid;
    @Value("${wechat.secret}")
    private String wechatSecret;
    @Value("${wechat.grantType}")
    private String wechatGrantType;

    @Value("${douyin.auth.code2Session-sandbox}")
    private String douyinCodeSessionSandBoxUrl;
    @Value("${douyin.auth.code2Session-product}")
    private String douyinCodeSessionProductUrl;
    @Value("${douyin.appid}")
    private String douyinAppid;
    @Value("${douyin.secret}")
    private String douyinSecret;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public WechatLoginRes jscodeToSession(String code) {
        Map<String,Object> params = new HashMap<>();
        params.put("appid",wechatAppid);
        params.put("secret",wechatSecret);
        params.put("js_code",code);
        params.put("grant_type",wechatGrantType);
        String ret = null;
        ret =  restTemplate.getForObject(wechatCodeSessionUrl+"?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}",String.class,params);
        return JSON.parseObject(ret,WechatLoginRes.class);
    }

    @Override
    public DyLoginRes jscodeToSession(String code, String anonymousCode) {
        Map<String,Object> params = new HashMap<>();
        params.put("appid",douyinAppid);
        params.put("secret",douyinSecret);
        params.put("code",code);
        params.put("anonymous_code",anonymousCode);
        String ret = null;
        ret =  restTemplate.postForObject(douyinCodeSessionSandBoxUrl,params,String.class);
        return JSON.parseObject(ret,DyLoginRes.class);
    }
}
